package com.slf.engine.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.springframework.web.context.WebApplicationContext;

import com.slf.engine.bo.Order;
import com.slf.engine.bo.WaitBean;
import com.slf.engine.common.SysContants;
import com.slf.engine.common.SysContext;
import com.slf.engine.services.IBusService;
import com.slf.engine.services.helper.ServiceHelper;
import com.slf.engine.services.impl.BusServiceImpl;
import com.slf.engine.utils.KeyedDigestMD5;

public class NoticeRecevAction extends Action{

	private static final Logger log = Logger.getLogger(NoticeRecevAction.class);
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 
	{
		// TODO Auto-generated method stub
		PrintWriter out = null;
		DynaActionForm orderForm = (DynaActionForm)form;
		String clientorderid = orderForm.getString("clientorderid");
		String state = orderForm.getString("state");
		log.log(Priority.INFO, "通知返回ip:" + request.getRemoteAddr() + " clientorderid：" + clientorderid + " state:" + state);
		String backMsg = "2";
		try {
			out = response.getWriter();
			
			IBusService busService = new BusServiceImpl((WebApplicationContext)this.servlet.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
			Order order = null;
//				从队列中移除
			synchronized (SysContext.QUERY_MAP) {
				WaitBean waitBean = SysContext.QUERY_MAP.get(clientorderid);
				if(waitBean != null)
				{
					order = waitBean.getOrder();
					waitBean.removeFromList();
				}
			}
			if(order != null)
			{
				if("ok".equals(state))
				{
					order.setClbz(SysContants.CZ_SUCCESS);
					order.setCljg("充值成功");
				}else if("no".equals(state)){
					order.setClbz(SysContants.CZ_FAILURE);
					order.setCljg("充值失败");
				}else{
					order.setClbz(SysContants.CZ_UNKNOW);
					order.setCljg("处理结果没有定义，status:" + state);
				}
				busService.doBusResult(order);
				backMsg = "1";
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "通知返回网络出现异常");
		}finally{
			if(out != null)
			{
				out.write(backMsg);
				out.flush();
				out.close();
			}
		}
		return null;
	}

}
